from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from users.Ser import *
from users.models import *
# Create your views here.

class NewsAPIView(APIView):
    def get(self, request):
        data=News.objects.all()
        data_ser=NewsSER(data,many=True)
        return Response(data_ser.data)

    def post(self, request):
        data = NewsSER(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'meg': '添加成功'})
        else:
            return Response({'meg': '添加失败'})


class AdvertisingAPIView(APIView):
    def get(self, request):
        page = request.GET.get('page', 1)
        size = request.GET.get('size', 2)
        data_start = (page - 1) * size
        data_end = page * size
        data = Advertising.objects.all()[data_start:data_end]
        total = Advertising.objects.count()
        ser = AdvertisingSER(data, many=True)
        return Response({'data': ser.data, 'total': total})

    def post(self, request):
        data = AdvertisingSER(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'msg': '添加成功'})
        else:
            return Response({'msg': '添加失败'})

